var app = getApp();
let Mcaptcha = require('../../utils/mcaptcha.js');
Page({
  data: {
    postOk: false,
    loginView: true,
    showRegister: true,
    smsInfo: true,
    disabled: false,

  },


  //注册
  getPhoneNumber: function(e) {
    let that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.showLoading({
        title: '注册中',
      })
      wx.login({
        success: function(res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: app.globalData.smsbaoApi + '/batch/sapi/getOpenId',
              method: 'post',
              data: {
                code: res.code
              },
              success: function(res) {
                wx.request({
                  url: app.globalData.smsbaoApi + '/batch/sapi/decryptData',
                  method: "post",
                  data: {
                    sessionKey: res.data.data.session_key,
                    encryptedData: e.detail.encryptedData,
                    iv: e.detail.iv
                  },
                  header: {
                    'content-type': 'application/json'
                  },
                  success: function(res) {
                    wx.hideLoading();
                    var phone = res.data.data;
                    phone  = phone.replace(" ","");

                    that.setData({
                      showRegister: !that.data.showRegister,
                      phone: phone,
                    })
                  }
                })
              }
            })
          }
        }
      });

    }
  },
  //注册成功
  smsUserPwdSubmit: function(e) {
    let that = this;  
    var phone =JSON.parse(that.data.phone);
    if (e.detail.value.sms_register_pwd == '' || e.detail.value.sms_register_pwd == undefined) {
      wx.showToast({
        title: '密码不能为空',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.setData({
        disabled: true,       
      })
      var smsData = {
        user: phone.phoneNumber,
        pwd: e.detail.value.sms_register_pwd,
        uPhone: phone.phoneNumber
      }
      var registerUrl = app.globalData.smsbaoApi + "/jwt/register.action?username=" + smsData.user + "&password=" + smsData.pwd + "&email=" + phone.phoneNumber + "@mobile.com" + "&qq=" + phone.phoneNumber + "&mobile=" + phone.phoneNumber;
      var header = {
        'content-type': 'application/json',
        'appId': app.globalData.appId,
        'appKey': app.globalData.appKey,
      }
      var method = 'POST';
      var i = 0;
      that.recursionRequest(registerUrl, '', method, header, smsData, i);
    }
  },
  //递归调用
  recursionRequest: function(url, data, method, header, smsData, i) {
    let that = this;
    if (i === 5 || that.data.postOK === true) {
      wx.showToast({
        title: '注册失败,联系客服',
        icon: 'none',
        duration: 2000
      })
      setTimeout(function() {
        wx.switchTab({
          url: '/pages/index/index'
        })
        that.setData({
          showRegister: !that.data.showRegister,
          disabled: false, 
        })
      }, 2500)
      return;
    } else {
      app.post(url, data, method, header).then((success_data) => {
        if (success_data.data.code == 200) {
          var info_url = app.globalData.smsbaoApi + "/jwt/member/info.action";
          var info_method = 'get';
          var info_header = {
            'content-type': 'application/json',
            'appId': app.globalData.appId,
            'appKey': app.globalData.appKey,
            "Authorization": success_data.header.token,
          }
          app.post(info_url, '', info_method, info_header).then((info_data) => {
            if (info_data.data.code == 200) {
              var smsUserInfo = {
                "userId": info_data.data.data.member.id,
                "username": info_data.data.data.member.username,
                "token": info_data.header.token,
                "balance": info_data.data.data.member.balance,
                "leaveCount": info_data.data.data.leaveCount,
              };
              wx.setStorageSync('smsInfo', smsUserInfo);
              wx.showToast({
                title: '注册成功',
                icon: 'loading',
                duration: 1000
              })
              setTimeout(function() {
                wx.switchTab({
                  url: '/pages/index/index'
                })
              }, 2000)
            } else {
              wx.showToast({
                title: info_data.data.desc,
                icon: 'none',
                duration: 1000
              })
            }
          })
          that.setData({
            postOk: true,
          })
        } else if (success_data.data.code == 400) {
          i++;
          var user = smsData.uPhone + "_" + i;
          var smsDataed = {
            user: user,
            pwd: smsData.pwd,
            uPhone: smsData.uPhone
          }
          var url = app.globalData.smsbaoApi + "/jwt/register.action?username=" + smsDataed.user + "&password=" + smsDataed.pwd + "&email=" + smsDataed.uPhone + "@mobile.com" + "&qq=" + smsDataed.uPhone + "&mobile=" + smsDataed.uPhone;
          this.recursionRequest(url, '', method, header, smsDataed, i);
        }
      })
    }

  },
  updYzm: function(e) {
    this.loginSmsUserYzm();
  },
  //更新资料
  onUsrUpd: function(e) {
    let that = this;
    var smsInfo = wx.getStorageSync('smsInfo');
    if (smsInfo == '' || smsInfo == undefined) {
      wx.showToast({
        title: "网络超时",
        icon: 'loading',
        duration: 2000
      })
    } else {
      that.getSmsUserInfo(smsInfo, 'upd');
    }
  },

  //获取用户信息
  getSmsUserInfo: function(smsInfo, upd = '') {
    let that = this;
    wx.request({
      url: app.globalData.smsbaoApi + "/jwt/member/info.action",
      method: 'get',
      header: {
        'content-type': 'application/json',
        'appId': app.globalData.appId,
        'appKey': app.globalData.appKey,
        "Authorization": smsInfo.token,
      },
      success: function(res) {
        if (res.data.code == '200') {
          var smsUserInfo = {
            "userId": res.data.data.member.id,
            "username": res.data.data.member.username,
            "token": res.header.token,
            "balance": res.data.data.member.balance,
            "leaveCount": res.data.data.leaveCount,
          };
          that.setData({
            smsInfo: smsUserInfo
          })
          wx.setStorageSync('smsInfo', smsUserInfo);
          if (upd) {
            wx.showToast({
              title: '更新成功',
              icon: 'none',
              duration: 2000
            })
          }

        } else {
          wx.showToast({
            title: res.data.desc,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },
  loginSmsUserYzm: function() {
    var num = "";
    for (var i = 0; i < 4; i++) {
      num += Math.floor(Math.random() * 10)
    }
    new Mcaptcha({
      el: 'canvas',
      width: 60,
      height: 30,
      code: num
    });
    this.setData({
      yzm: num
    })
  },
  //登陆
  formLogin: function(data) {
    let that = this;
    var username = data.detail.value.sms_user;
    var password = data.detail.value.sms_pwd;
    var yzm = data.detail.value.sms_yzm;
    if (username == '' || username == undefined) {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'none',
        duration: 2000
      })
    } else if (password == '' || password == undefined) {
      wx.showToast({
        title: '账号或密码错误',
        icon: 'none',
        duration: 2000
      })
    } else if (yzm == '' || yzm == undefined) {
      wx.showToast({
        title: '验证码错误',
        icon: 'none',
        duration: 2000
      })
      this.loginSmsUserYzm();
    } else {
      if (yzm == that.data.yzm) {
        wx.request({
          url: app.globalData.smsbaoApi + "/jwt/login.action?username=" + username + "&password=" + password,
          method: 'post',
          header: {
            'content-type': 'application/json',
            'appId': app.globalData.appId,
            'appKey': app.globalData.appKey,
          },
          success: function(res) {
            var smsUserInfo = {};
            if (res.data.code == '200') {
              wx.request({
                url: app.globalData.smsbaoApi + "/jwt/member/info.action",
                method: 'get',
                header: {
                  'content-type': 'application/json',
                  'appId': app.globalData.appId,
                  'appKey': app.globalData.appKey,
                  "Authorization": res.header.token,
                },
                success: function(resInfo) {
                  if (resInfo.data.code == '200') {
                    smsUserInfo = {
                      "userId": resInfo.data.data.member.id,
                      "username": resInfo.data.data.member.username,
                      "token": resInfo.header.token,
                      "balance": resInfo.data.data.member.balance,
                      "leaveCount": resInfo.data.data.leaveCount,
                    };
                    wx.setStorageSync('smsInfo', smsUserInfo);
                    wx.showToast({
                      title: '登录成功',
                      icon: 'loading',
                      duration: 1000
                    })
                    setTimeout(function() {

                      wx.switchTab({
                        url: '/pages/index/index'
                      })
                    }, 2000);
                  }
                }
              })
            } else {
              wx.showToast({
                title: res.data.desc,
                icon: 'none',
                duration: 2000
              })
            }
          }
        })
      } else {
        wx.showToast({
          title: '验证码错误',
          icon: 'none',
          duration: 2000
        })
        this.loginSmsUserYzm();
      }

    }
  },
  registerSms: function(e) {
    this.setData({
      loginView: !this.data.loginView,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function(options) {
    this.loginSmsUserYzm();
    var smsInfo = wx.getStorageSync('smsInfo');
    if (smsInfo == '' || smsInfo == undefined) {
      this.setData({
        smsInfo: false,
      })
    } else {
      if (smsInfo.leaveCount < 0) {
        wx.showToast({
          title: "短信条数不足，请尽快充值",
          icon: 'none',
          duration: 2000
        })
      }
      this.getSmsUserInfo(smsInfo);
    }
  },
  onHide: function(option) {
    var smsInfo = wx.getStorageSync('smsInfo');
    if (smsInfo == '' || smsInfo == undefined) {
      this.setData({
        smsInfo: false,
      })
    } else {
      this.getSmsUserInfo(smsInfo);
    }
  },

})